package org.zju.demo.shoppingdemo.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import org.zju.demo.shoppingdemo.R;
import org.zju.demo.shoppingdemo.adapter.AddressListAdapter;
import org.zju.demo.shoppingdemo.model.Address;
import org.zju.demo.shoppingdemo.model.response.BaseResponse;

import java.util.List;

/**
 * Created by ZJDX on 2015/9/11.
 */
public class AddressManagementActivity extends CommonActivity {

    private static final int REQUEST_ADD = 0;

    private static final int REQUEST_UPDATE = 1;

    private ListView addressListView = null;

    private ImageView addAddressView = null;
    private ImageView backView = null;

    private FrameLayout notice = null;
    private FrameLayout listFrame = null;

    private String username = null;

    private List<Address> addressList = null;
    AddressListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 不显示标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.usercenter_addresslist);

        Intent intent = this.getIntent();
        username = intent.getStringExtra("username");
        // prepare data
        loadData();
        adapter = new AddressListAdapter(this, addressList);
        // bind addressListView to adapter
        addressListView = (ListView) findViewById(R.id.address_manage_list);
        addressListView.setAdapter(adapter);

        addAddressView = (ImageView) findViewById(R.id.address_manage_add);
        addAddressView.setOnClickListener(new AddressListener());
        backView = (ImageView) findViewById(R.id.address_manage_back);
        backView.setOnClickListener(new AddressListener());

        initBottomMenu();
        initListViewEvent();

        notice = (FrameLayout) findViewById(R.id.address_manage_notice);
        listFrame = (FrameLayout) findViewById(R.id.address_manage_listframe);
        Log.i("AddressManagement", Integer.toString(addressList.size()));
        if (addressList.size() == 0) {
            notice.setVisibility(View.VISIBLE);
            listFrame.setVisibility(View.GONE);
        } else {
            notice.setVisibility(View.GONE);
            listFrame.setVisibility(View.VISIBLE);
        }
    }

    private void loadData(){
        addressList = Address.findWithQuery(Address.class, "Select * from Address where username = ?", username);
        if (addressList.size() == 0) {
            return;
        }
        int index = 0;
        for(int i = 0; i < addressList.size(); ++ i) {
            if (addressList.get(i).getDefaultAddress() == 1) {
                index = i;
                break;
            }
        }
        //将默认地址设置在ListView的第一条
        if (index != 0) {
            Address tmp = addressList.get(index);
            addressList.set(index, addressList.get(0));
            addressList.set(0, tmp);
        }
    }

    public void initListViewEvent() {
        addressListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // jump to updateAddress activity
                Log.e("listViewEvent", Integer.toString(position));
                Address address = addressList.get(position);
                Intent intent = new Intent();
                long addressId = address.getId();
                // pass the id and the position of address to modify
                intent.putExtra("position", Integer.toString(position));
                intent.putExtra("id", Long.toString(addressId));
                intent.setClass(AddressManagementActivity.this, UpdateAddressActivity.class);
                startActivityForResult(intent, REQUEST_UPDATE);
            }
        });
    }

    class AddressListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.address_manage_add:
                    Intent intent = new Intent();
                    intent.putExtra("username", username);
                    intent.setClass(AddressManagementActivity.this, AddAddressActivity.class);
                    startActivityForResult(intent, REQUEST_ADD);
                    break;
                case R.id.address_manage_back:
                    finish();
                default:
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_ADD:
                if (resultCode == RESULT_OK) {
                    // refresh the ListView component
                    String result = data.getStringExtra("id");
                    Address address = Address.findById(Address.class, Long.parseLong(result));
                    // add to the addressList
                    addressList.add(address);
                    Log.e("AddressManagement", "REQUEST_ADD");
                    Log.i("AddressManagement", result);
                    listFrame.setVisibility(View.VISIBLE);
                    notice.setVisibility(View.GONE);
                    adapter.notifyDataSetChanged();
                }
                break;
            case REQUEST_UPDATE:
                int position = Integer.parseInt(data.getStringExtra("position"));
                assert(position >= 0);
                long id = Long.parseLong(data.getStringExtra("id"));
                // get the updated object
                Address defaultAddress = Address.findById(Address.class, id);
//                assert(defaultAddress != null);
                if (defaultAddress != null) {
                    //update the addressList
                    if (defaultAddress.getDefaultAddress() == 1) {
                        if (position != 0) {
                            addressList.get(0).setDefaultAddress(0);
                            //交换位置
                            addressList.set(position, addressList.get(0));
                            addressList.set(0, defaultAddress);
                        } else {
                            addressList.set(0, defaultAddress);
                        }
                    }
                    Log.i("REQUEST_UPDATE", Long.toString(id) + " " + Integer.toString(position));
                } else {
                    addressList.remove(position);
                    if (addressList.size() == 0 ) {
                        notice.setVisibility(View.VISIBLE);
                        listFrame.setVisibility(View.GONE);
                    }
                }
                adapter.notifyDataSetChanged();
                break;
            default:
        }
    }
    @Override
    public void onResponseMessage(BaseResponse response) {
        super.onResponseMessage(response);
    }

    @Override
    public void initBottomMenu() {
    }
}
